package com.example;

import javafx.scene.image.WritableImage;
import javafx.scene.robot.Robot;
import javafx.scene.shape.Rectangle;
import org.opencv.core.Mat;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

/**
 * <p>滚动处理</p>
 *
 * @author dc
 * @date 2025-09-25
 **/
public class ScrollHandler {
    private static ScrollHandler scrollHandler;
    private final PaneManager paneManager = PaneManager.getInstance();
    /**
     * 当前滚动位置
     */
    public int currentScrollPosition = 0;
    /**
     * 最小滚动位置
     */
    public int minScrollSteps = 0;
    /**
     * 最大滚动位置
     */
    public int maxScrollSteps = 0;
    /**
     * 是否已到达底部
     */
    public boolean isReachBottom = false;
    /**
     * 是否已到达顶部
     */
    public boolean isReachTop = false;

    /**
     * 保存下滚时的截图
     */
    private final List<Mat> downScrollFrameList = new ArrayList<>(50);
    /**
     * 保存上滚时的截图
     */
    private final List<Mat> upScrollFrameList = new ArrayList<>(50);

    private ScheduledExecutorService executorService;
    
    public List<Mat> getDownScrollFrameList() {
        return downScrollFrameList;
    }
    public List<Mat> getUpScrollFrameList() {
        return upScrollFrameList;
    }
    public static ScrollHandler getScrollHandler() {
        return scrollHandler;
    }
    /**
     * 创建新实例，刷新数据
     */
    public static void createNewScrollHandler() {
        scrollHandler = new ScrollHandler();
    }
    
    
    /**
     * 获取指定区域截图，每一次并不截图整个区域，而是截取指定高度
     * @throws IllegalStateException 如果当前函数没有运行于 JavaFX UI线程，则抛出此异常
     * @return 截图
     */
    public WritableImage getFrame() {
        Rectangle selectionRect = paneManager.getSelectionRect();
        Robot robot = new Robot();
        return robot.getScreenCapture(null, selectionRect.getX(), selectionRect.getY(),
                selectionRect.getWidth(), CaptureProperty.SCROLL_FRAME_HEIGHT);
    }
    /**
     * 获取剩余区域截图
     * @throws IllegalStateException 如果当前函数没有运行于 JavaFX UI线程，则抛出此异常
     * @return 截图
     */
    public WritableImage getRemainedFrame() {
        Rectangle selectionRect = paneManager.getSelectionRect();
        Robot robot = new Robot();
        return robot.getScreenCapture(null, selectionRect.getX(), selectionRect.getY() + CaptureProperty.SCROLL_FRAME_HEIGHT,
                selectionRect.getWidth(), selectionRect.getHeight() - CaptureProperty.SCROLL_FRAME_HEIGHT);
    }

    /**
     * 判断上下滚动，下滚动截图存于一个列表，上滚动截图存于一个列表
     * @param frame 截图
     * @param wheelRotation 滚动方向 1为下滚，-1为上滚
     */
    public void saveFrame(Mat frameMat, int wheelRotation) {
        if (wheelRotation > 0) {
            downScrollFrameList.add(frameMat);
        } else {
            upScrollFrameList.add(frameMat);
        }
    }

}
